﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
//using System.Collections;
using System.Xml;
using System.Web.Services;

public partial class Finance_wasteBook : System.Web.UI.Page
{
    Function f = new Function();
    ZSql zs = new ZSql();
    protected void Page_Load(object sender, EventArgs e)
    {
        lblPath.Text = f.getModuleidAdd(Request.QueryString["moduid"].ToString());
        hfxs.Value = Request.QueryString["moduid"].ToString();
        if (!IsPostBack)
        {
            HidWareid.Value = getWareId();
            initData();
            inDepartment();
            txtKdate.Text = Request.QueryString["Kdate"];
            txtJdate.Text = Request.QueryString["Jdate"];
            financeCode.Text = Request.QueryString["financeCode"];
            UserName.Text = Request.QueryString["UserName"];
            financeType.SelectedValue = Request.QueryString["financeType"];
            departmentId.SelectedValue = Request.QueryString["departmentId"];
        }
    }


    private void inDepartment()
    {
        ZSql Dep = new ZSql();
        Dep.Open("select * from Department");
        departmentId.DataSource = Dep.m_table;
        departmentId.DataTextField = "Deptname";
        departmentId.DataValueField = "Deptid";
        departmentId.DataBind();
        departmentId.Items.Insert(0, new ListItem("所有部门", ""));
        Dep.Close();
    }

    private void initData()
    {
        string search = "";
        string countSqlIn = "";
        string countSqlOut = "";
        float FcountMoneyIn = 0, FcountMoneyOut = 0;
        string sql = "select * from (select a.*,(select StaffName from CS_Staff where StaffId=a.userId) as  UserName,(select deptName from department where a.departmentId=deptid) as departmentName  from CS_wasteBook a )TblSales where 1=1 ";

        if (!string.IsNullOrEmpty(Request.QueryString["Kdate"]) && !string.IsNullOrEmpty(Request.QueryString["Jdate"]))//时间起止
        {
            search += "&Kdate=" + Request.QueryString["Kdate"].Trim();
            search += "&Jdate=" + Request.QueryString["Jdate"].Trim();
            sql += " and CONVERT(char(10), EditDate, 120)>='" + Request.QueryString["Kdate"] + "' and CONVERT(char(10), EditDate, 120)<='" + Request.QueryString["Jdate"] + "' ";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["financeCode"]))//订单号
        {
            search += "&financeCode=" + Request.QueryString["financeCode"].Trim();
            sql += " and financeCode like '%" + Request.QueryString["financeCode"].Trim() + "%'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["UserName"]))//客户名称
        {
            search += "&UserName=" + Request.QueryString["UserName"].Trim();
            sql += " and UserName like '%" + Request.QueryString["UserName"].Trim() + "%'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["financeType"]))//财务类型
        {
            search += "&financeType='" + Request.QueryString["financeType"].Trim();
            sql += " and financeType='" + Request.QueryString["financeType"].Trim() + "'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["departmentId"]))//部门
        {
            search += "&departmentId=" + Request.QueryString["departmentId"].Trim();
            sql += " and departmentId=" + Request.QueryString["departmentId"].Trim();
        }
        //统计countSql：countMoneyIn，countMoneyOut
        countSqlIn = "select isnull(sum(financeMoney),0) as countMoneyIn from(" + sql + ") DERIVEDTBL where financeType='+'";////收入
        countSqlOut = "select isnull(sum(financeMoney),0) as countMoneyOut from(" + sql + ") DERIVEDTBL where financeType='-'";////支出
        sql += " order by wasteBookId desc";

        PageNavigator1.Url = "../Finance/wasteBook.aspx?moduid=" + hfxs.Value + search;
        PageNavigator1.Total = 1;
        PageNavigator1.Query = sql;
        //合计支出收入情况
        //读取统计数据
        //收入
        //Response.Write(sql);
        zs.Open(countSqlIn);
        if (zs.m_table.Rows.Count > 0)
        {
            FcountMoneyIn = Convert.ToInt32(zs.m_table.Rows[0]["countMoneyIn"]);
            countMoneyIn.Text = zs.m_table.Rows[0]["countMoneyIn"].ToString();
        }
        zs.Close();
        //支出
        zs.Open(countSqlOut);
        if (zs.m_table.Rows.Count > 0)
        {
            FcountMoneyOut = Convert.ToInt32(zs.m_table.Rows[0]["countMoneyOut"]);
            countMoneyOut.Text = zs.m_table.Rows[0]["countMoneyOut"].ToString();
        }
        zs.Close();
        countMoney.Text = (FcountMoneyIn - FcountMoneyOut).ToString();//合计余额

    }
    private string getWareId()
    {
        ZSql zs = new ZSql();
        string sql = "select WarehouseId from UserInfo where userid=" + Request.Cookies["user"].Values["id"];
        zs.Open(sql);

        zs.Close();
        return zs.m_table.Rows[0]["WarehouseId"].ToString();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string search = "";
        if (!string.IsNullOrEmpty(txtKdate.Text) && !string.IsNullOrEmpty(txtJdate.Text.Trim()))//时间起止
        {
            search += "&Kdate=" + txtKdate.Text.Trim();
            search += "&Jdate=" + txtJdate.Text.Trim();
        }
        if (!string.IsNullOrEmpty(financeCode.Text.Trim()))//订单号
        {
            search += "&financeCode=" + Common.FormatParameter(financeCode.Text.Trim());
        }
        if (!string.IsNullOrEmpty(UserName.Text.Trim()))//客户名称
        {
            search += "&UserName=" + Common.FormatParameter(UserName.Text).Trim();
        }
        if (!string.IsNullOrEmpty(financeType.SelectedValue))//财务类型
        {
            search += "&financeType=" + Common.FormatParameter(financeType.SelectedValue.Trim());
        }

        if (!string.IsNullOrEmpty(departmentId.SelectedValue))//部门
        {
            search += "&departmentId=" + Common.FormatParameter(departmentId.SelectedValue.Trim());
        }

        PageNavigator1.Url = "../Finance/wasteBook.aspx?moduid=" + hfxs.Value + search;
        Response.Redirect("wasteBook.aspx?moduid=" + hfxs.Value + search);
    }


    protected void GvData_RowDataBound(object sender, GridViewRowEventArgs e)//在邦定数据
    {
        //f.checkLevels(Request.Cookies["user"].Values["roleid"], hfxs.Value, 4, GvDataType, btndel, btnallflag, btnAdd);//权限
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int typeSale = Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "AuditState"));
            if (typeSale == 0)
            {
                e.Row.Cells[8].Text = "未审核";
            }
            else if (typeSale == 1)
            {
                e.Row.Cells[8].Text = "已通过";
            }
            else if (typeSale == 2)
            {
                e.Row.Cells[8].Text = "未通过";
            }
            string financeType = DataBinder.Eval(e.Row.DataItem, "financeType").ToString();
            if (financeType == "+")
            {
                e.Row.Cells[3].Text = "收入";
            }
            else
            {
                e.Row.Cells[4].Text = e.Row.Cells[3].Text.ToString() + e.Row.Cells[4].Text.ToString();
                e.Row.Cells[3].Text = "支出";
            }

        }
    }


    protected void Excel_Click(object sender, EventArgs e)//导出Excel
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=wasteBook" + DateTime.Now.Date.ToString("yyyyMMdd") + ".xls");
        // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码！！！
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        //  turn off paging 

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        this.GvData.RenderControl(htw);
        string strHtml = sw.ToString().Trim();
        Response.Output.Write(strHtml);
        Response.Flush();
        Response.End();
        // turn the paging on again 

    }
    //添加一个空方法,防止   GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内错误
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm. control is rendered for
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect("wasteBookAdd.aspx?moduid=" + hfxs.Value + "&action=add");
    }
    protected void btnallflag_Click(object sender, EventArgs e)
    {
        ZSql allflag = new ZSql();
        int n = 0;
        if (this.GvData.Rows.Count > 0)
        {
            for (int i = 0; i < GvData.Rows.Count; i++)
            {
                CheckBox ck = GvData.Rows[i].FindControl("ckFlag") as CheckBox;
                if (ck.Checked)
                {
                    int flag = 1;
                    allflag.Open("update CS_wasteBook set AuditState=" + flag + " where wasteBookId=" + this.GvData.Rows[i].Cells[0].Text);
                    ClientScript.RegisterStartupScript(typeof(Page), "aa", "alert('审核成功');", true);
                }
                else
                {
                    n++;
                }

                if (n == this.GvData.Rows.Count)
                {

                    ClientScript.RegisterStartupScript(typeof(Page), "aa", "alert('至少应选择一项')", true);
                }


            }
        }
    }
    protected void linkbtnUpdate_Click(object sender, EventArgs e)//修改
    {
        string id = (sender as LinkButton).CommandArgument;
        Response.Redirect("wasteBookAdd.aspx?id=" + id + "&action=update&moduid=" + Request.QueryString["moduid"]);
    }

    protected void lnkbtnFlag_Click(object sender, EventArgs e)//审核
    {
        string id = (sender as LinkButton).CommandArgument;
        Response.Redirect("wasteBookAdd.aspx?id=" + id + "&action=flag&moduid=" + Request.QueryString["moduid"]);
    }

    protected void btndel_Click(object sender, EventArgs e)//删除
    {
        int n = 0;
        if (this.GvData.Rows.Count > 0)
        {
            for (int i = 0; i < GvData.Rows.Count; i++)
            {
                CheckBox ck = GvData.Rows[i].FindControl("ckFlag") as CheckBox;
                if (ck.Checked)
                {
                    string id = this.GvData.Rows[i].Cells[0].Text;
                    zs.Open("delete CS_wasteBook  where wasteBookId=" + id);
                    ClientScript.RegisterStartupScript(typeof(Page), "aa", "alert('删除成功');", true);
                }
                else
                {
                    n++;
                }
                if (n == this.GvData.Rows.Count)
                {

                    ClientScript.RegisterStartupScript(typeof(Page), "aa", "alert('至少应选择一项')", true);
                }
            }
        }
        zs.Close();
    }
}
